package com.shexianyu.simple;

/**
 * 121. 买卖股票的最佳时机
 */
public class MaxProfit {

    /**
     * 超出时间限制
     *
     * @param prices
     * @return
     */
    public int maxProfit(int[] prices) {
        int cnt = 1;
        int res = 0;
        int max = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            /*if (prices[i] > prices[i + 1]) {
                cnt++;
                if (cnt == prices.length) {
                    return 0;
                }
            }*/
            for (int j = prices.length - 1; j > i; j--) {
                max = prices[j] - prices[i];
                res = Math.max(res, max);
            }
        }
        if (res <= 0)
            return 0;
        return res;
    }

    //7, 1, 5, 3, 6, 4
    public int maxProfit1(int[] prices) {
        int min = Integer.MAX_VALUE;
        int max = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < min) {
                min = prices[i];
            } else if (prices[i] - min > max) {
                max = prices[i] - min;
            }
        }
        return max;
    }

    public int maxProfit2(int[] prices) {
        int max = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int res = prices[j] - prices[i];
                if (res > max) {
                    max = res;
                }
            }
        }
        return max;
    }
}
